<template>
  <div class="app-container profile-container">
    <!-- 顶部标题 -->
<!--    <div class="profile-header">-->
<!--      <h2>实名认证信息</h2>-->
<!--      <el-button-->
<!--        type="primary"-->
<!--        size="small"-->
<!--        @click="handleEdit"-->
<!--        v-if="form && form.name"-->
<!--      >-->
<!--        <i class="el-icon-edit"></i>-->
<!--        编辑信息-->
<!--      </el-button>-->
<!--    </div>-->
    <div class="profile-header">
      <h2>实名认证信息</h2>
      <el-button
        type="primary"
        size="small"
        @click="handleEdit"
      >
        <i class="el-icon-edit"></i>
        {{ form.name ? '编辑信息' : '实名认证' }}
      </el-button>
    </div>
    <!-- 主内容区 -->
    <div class="profile-content">
      <!-- 左侧个人信息卡片 -->
      <div class="profile-card">
        <el-card shadow="hover" class="user-card">
          <div class="user-avatar">
            <el-avatar :size="100" :src="dicebearAvatarUrl" />
            <h3 class="user-name">{{ form.name || '未认证用户' }}</h3>
<!--            <div class="verification-badge">-->
<!--              <i class="el-icon-success success-icon"></i>-->
<!--              <span>已实名认证</span>-->
<!--            </div>-->
            <div class="verification-badge">
              <i :class="form.name ? 'el-icon-success success-icon' : 'el-icon-error error-icon'"></i>
              <span>{{ form.name ? '已实名认证' : '未实名认证' }}</span>
            </div>
          </div>

          <el-divider />

          <div class="user-meta">
            <div class="meta-item">
              <i class="el-icon-user"></i>
              <span>性别: {{ form.gender || '未填写' }}</span>
            </div>
            <div class="meta-item">
              <i class="el-icon-date"></i>
              <span>认证时间: {{ form.createTime ? parseTime(form.createTime) : '未记录' }}</span>
            </div>
            <div class="meta-item">
              <i class="el-icon-location"></i>
              <span>所在区县: {{ form.county || '未填写' }}</span>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 右侧详细信息 -->
      <div class="detail-card">
        <el-card shadow="hover">
          <!-- 基本信息 -->
          <div class="detail-section">
            <h3 class="section-title">
              <i class="el-icon-document"></i>
              基本信息
            </h3>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="真实姓名" label-class-name="desc-label">
                <span class="info-value">{{ form.name || '-' }}</span>
              </el-descriptions-item>

              <el-descriptions-item label="身份证号" label-class-name="desc-label">
                <span class="info-value">{{ idNumberFormat(form.idNumber) }}</span>
              </el-descriptions-item>

              <el-descriptions-item label="手机号码" label-class-name="desc-label">
                <span class="info-value">{{ phoneFormat(form.phoneNumber) }}</span>
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <el-divider />

          <!-- 资产信息 -->
          <div class="detail-section">
            <h3 class="section-title">
              <i class="el-icon-money"></i>
              资产信息
            </h3>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="年收入" label-class-name="desc-label">
                <span class="info-value">{{ form.annualIncome ? `${form.annualIncome}元` : '-' }}</span>
              </el-descriptions-item>

              <el-descriptions-item label="学历" label-class-name="desc-label">
                <span class="info-value">{{ form.education || '-' }}</span>
              </el-descriptions-item>

              <el-descriptions-item label="资产情况" label-class-name="desc-label">
                <div class="asset-tags">
                  <el-tag
                    :type="form.hasHouse ? 'success' : 'info'"
                    size="small"
                  >
                    <i :class="form.hasHouse ? 'el-icon-house' : 'el-icon-office-building'"></i>
                    {{ form.hasHouse ? '有房产' : '无房产' }}
                  </el-tag>
                  <el-tag
                    :type="form.hasCar ? 'success' : 'info'"
                    size="small"
                    style="margin-left: 8px"
                  >
                    <i :class="form.hasCar ? 'el-icon-van' : 'el-icon-bicycle'"></i>
                    {{ form.hasCar ? '有车' : '无车' }}
                  </el-tag>
                </div>
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>
      </div>
    </div>
    <!-- Edit Dialog -->
<!--    <el-dialog-->
<!--      :visible.sync="editDialogVisible"-->
<!--      title="编辑实名认证信息"-->
<!--      width="600px"-->
<!--      :close-on-click-modal="false"-->
<!--    >-->
    <el-dialog
      :visible.sync="editDialogVisible"
      :title="form.name ? '编辑实名认证信息' : '实名认证'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="120px"
        label-position="right"
      >
        <el-form-item label="真实姓名" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入真实姓名" />
        </el-form-item>

        <el-form-item label="身份证号" prop="idNumber">
          <el-input
            v-model="editForm.idNumber"
            placeholder="请输入18位身份证号码"
            maxlength="18"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="手机号码" prop="phoneNumber">
          <el-input
            v-model="editForm.phoneNumber"
            placeholder="请输入11位手机号码"
            maxlength="11"
          />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="editForm.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="所在区县" prop="county">
          <el-input v-model="editForm.county" placeholder="请输入所在区县" />
        </el-form-item>

        <el-form-item label="年收入(元)" prop="annualIncome">
          <el-input-number
            v-model="editForm.annualIncome"
            :min="0"
            :step="10000"
            :precision="0"
            controls-position="right"
          />
        </el-form-item>

        <el-form-item label="学历" prop="education">
          <el-select v-model="editForm.education" placeholder="请选择学历">
            <el-option label="初中及以下" value="初中及以下" />
            <el-option label="高中/中专" value="高中/中专" />
            <el-option label="大专" value="大专" />
            <el-option label="本科" value="本科" />
            <el-option label="硕士" value="硕士" />
            <el-option label="博士及以上" value="博士及以上" />
          </el-select>
        </el-form-item>

        <el-form-item label="资产情况">
          <el-checkbox v-model="editForm.hasHouse">有房产</el-checkbox>
          <el-checkbox v-model="editForm.hasCar" style="margin-left: 20px">有车</el-checkbox>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getCurrentUserRealInfo } from "@/api/user_profile/user_auth.js"
import {updateCurrentUserRealInfo} from "@/api/user_profile/user_profile.js";
// import dayjs from "dayjs"
import moment from 'moment'
import pinyin from 'pinyin';

export default {
  data() {
    return {
      form: {
        name: '',
        idNumber: '',
        phoneNumber: '',
        gender: '',
        annualIncome: null,
        county: '',
        education: '',
        hasHouse: false,
        hasCar: false,
        createTime: null
      },
      avatarUrl: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      loading: true,
      editDialogVisible: false,
      editForm: {
        name: '',
        idNumber: '',
        phoneNumber: '',
        gender: '',
        annualIncome: null,
        county: '',
        education: '',
        hasHouse: false,
        hasCar: false
      },
      editRules: {
        name: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        idNumber: [
          { required: true, message: '请输入身份证号码', trigger: 'blur' },
          { pattern: /^\d{17}[\dXx]$/, message: '请输入正确的18位身份证号码', trigger: 'blur' }
        ],
        phoneNumber: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        county: [
          { required: true, message: '请输入所在区县', trigger: 'blur' }
        ],
        annualIncome: [
          { required: true, message: '请输入年收入', trigger: 'blur' }
        ],
        education: [
          { required: true, message: '请选择学历', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    // 根据中文名生成 DiceBear 头像 URL
    dicebearAvatarUrl() {
      // 确保 form.name 存在且不为空
      if (this.form.name && typeof this.form.name === 'string' && this.form.name.trim() !== '') {
        // 使用 pinyin 库将中文名转换为拼音
        // STYLE_NORMAL: 不带声调
        // compact: true: 将每个字的拼音直接连接起来，如 "张三" -> "zhangsan"
        const pinyinArray = pinyin(this.form.name, {
          style: pinyin.STYLE_NORMAL,
          compact: true
        });

        // 将拼音数组展平并连接成字符串，去除可能的空格
        const pinyinString = pinyinArray.flat().join('').replace(/\s/g, '');

        // 如果拼音字符串为空（例如，name是非中文的特殊字符），则返回默认头像
        if (!pinyinString) {
          return this.avatarUrl;
        }

        // 拼接 DiceBear URL，使用 'pixel-art' 风格，您可以更换其他风格
        return `https://api.dicebear.com/8.x/pixel-art/svg?seed=${pinyinString}`;
      }
      // 如果 name 为空、不是字符串或为空字符串，则返回备用默认头像
      return this.avatarUrl;
    }
  },
  created() {
    this.loadData()
  },
  methods: {
    // async loadData() {
    //   try {
    //     const res = await getCurrentUserRealInfo();
    //     if (res.code === 200) {
    //       this.form = res.data;
    //       // 根据性别设置默认头像
    //       if (this.form.gender === '男') {
    //         this.avatarUrl = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png';
    //       } else if (this.form.gender === '女') {
    //         this.avatarUrl = 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png';
    //       }
    //     } else {
    //       this.$message.error(res.msg || "获取实名信息失败");
    //     }
    //   } catch (error) {
    //     console.error("获取实名信息出错:", error);
    //     this.$message.error("获取信息失败，请稍后重试");
    //   } finally {
    //     this.loading = false;
    //   }
    // },
    async loadData() {
      try {
        const res = await getCurrentUserRealInfo();
        if (res.code === 200) {
          // 使用对象展开运算符确保所有字段都有值
          this.form = {
            ...this.form, // 保留初始值
            ...res.data   // 覆盖API返回的数据
          };

          // 根据性别设置默认头像
          if (this.form.gender === '男') {
            this.avatarUrl = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png';
          } else if (this.form.gender === '女') {
            this.avatarUrl = 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png';
          }
        } else {
          this.$message.error(res.msg || "获取实名信息失败");
        }
      } catch (error) {
        console.error("获取实名信息出错:", error);
        // this.$message.error("获取信息失败，请稍后重试");
      } finally {
        this.loading = false;
      }
    },
    idNumberFormat(val) {
      if (!val) return '-'
      return val.replace(/^(.{4})(?:\d+)(.{4})$/, '$1********$2')
    },
    phoneFormat(val) {
      if (!val) return '-'
      return val.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
    },
    // parseTime(time) {
    //   if (!time) return '-'
    //   return dayjs(time).format('YYYY-MM-DD HH:mm')
    // },
    // 修改 parseTime 方法为：
    parseTime(time) {
      if (!time) return '-'
      return moment(time).format('YYYY-MM-DD HH:mm')
    },
    handleEdit() {
      // Copy current form data to edit form
      this.editForm = {
        name: this.form.name,
        idNumber: this.form.idNumber,
        phoneNumber: this.form.phoneNumber,
        gender: this.form.gender,
        annualIncome: this.form.annualIncome,
        county: this.form.county,
        education: this.form.education,
        hasHouse: this.form.hasHouse || false,
        hasCar: this.form.hasCar || false
      }
      this.editDialogVisible = true
    },

    submitEditForm() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (valid) {
          try {
            const res = await updateCurrentUserRealInfo(this.editForm)
            if (res.code === 200) {
              this.$message.success('修改成功')
              this.loadData() // Refresh the data
              this.editDialogVisible = false

              // 新增：通知信用分页面刷新任务列表
              this.$bus.$emit('real-name-auth-updated', true);
            } else {
              // this.$message.error(res.msg || '修改失败')
            }
          } catch (error) {
            console.error('修改实名信息出错:', error)
            // this.$message.error('修改失败，请稍后重试')
          }
        } else {
          this.$message.warning('请填写完整的表单信息')
          return false
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.profile-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.profile-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;

  h2 {
    color: #333;
    font-size: 24px;
    font-weight: 500;
  }
}

.profile-content {
  display: flex;
  gap: 20px;

  @media (max-width: 768px) {
    flex-direction: column;
  }
}

.profile-card {
  flex: 0 0 300px;

  @media (max-width: 768px) {
    flex: auto;
  }
}

.detail-card {
  flex: 1;
}

.user-card {
  border-radius: 8px;
  border-top: 3px solid var(--el-color-primary);

  .user-avatar {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 16px 0;

    .user-name {
      margin: 12px 0 8px;
      color: #333;
      font-size: 18px;
    }

    .verification-badge {
      display: flex;
      align-items: center;
      background: #f6ffed;
      padding: 4px 12px;
      border-radius: 16px;
      color: #52c41a;
      font-size: 14px;

      .success-icon {
        margin-right: 6px;
        font-size: 16px;
      }
    }
  }

  .user-meta {
    .meta-item {
      display: flex;
      align-items: center;
      margin-bottom: 12px;
      color: #666;

      .el-icon {
        margin-right: 8px;
        color: var(--el-color-primary);
      }

      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}

.detail-section {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }

  .section-title {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    color: #333;
    font-size: 18px;
    font-weight: 500;

    .el-icon {
      margin-right: 8px;
      color: var(--el-color-primary);
    }
  }
}

.desc-label {
  background: #f5f7fa !important;
  font-weight: 500;
}

.info-value {
  font-size: 14px;
  color: #333;
}

.asset-tags {
  display: flex;
  align-items: center;
}

.el-divider {
  margin: 20px 0;
}

.el-dialog {
  border-radius: 8px;

  .el-form-item {
    margin-bottom: 22px;
  }

  .el-input-number {
    width: 100%;
  }

  .el-select {
    width: 100%;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.verification-badge {
  display: flex;
  align-items: center;
  padding: 4px 12px;
  border-radius: 16px;
  font-size: 14px;

  &.verified {
    background: #f6ffed;
    color: #52c41a;
  }

  &.unverified {
    background: #fff2f0;
    color: #ff4d4f;
  }

  .success-icon {
    margin-right: 6px;
    font-size: 16px;
    color: #52c41a;
  }

  .error-icon {
    margin-right: 6px;
    font-size: 16px;
    color: #ff4d4f;
  }
}
</style>
